//
//  LLHomeTableViewController.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/6/23.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit

// cell 可重用标识符
private let statusCellId = "cell"

class LLHomeTableViewController: LLVisitorTableViewController {

    //创建 refresh 下拉刷新
    let refresh = LLRefresh()
    
    //定义一个数组，存储数据
    var statuArray = [LLStatusesModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //判断是否登录
        if !isLogin {
            
            visitorView?.setVisitorView(nil, title: nil)
            
            return
        }
        
        setupTableViewInfo()
        
        //加载数据
        loadStatusData(activityView.isAnimating())
    }
    
    //注册
    func setupTableViewInfo(){
        
        tableView.registerClass(LLStautsCell.self, forCellReuseIdentifier: statusCellId)
        
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 200
        
        //设置分割线
        tableView.separatorStyle = .None
        
        //设置footerview
        tableView.tableFooterView = activityView

        //添加监听事件
        refresh.addTarget(self, action: "refreshAction", forControlEvents: UIControlEvents.ValueChanged)
        
        tableView.addSubview(refresh)

    }
    
    //监听方法
    @objc func refreshAction(){
        
        loadStatusData(activityView.isAnimating())

    }
 
    //懒加载 上拉加载更多
    private lazy var activityView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view.color = ThemeColor
        
        return view
    }()
    
    // 条数
    private lazy var pullDownTipLabel: UILabel = {
        let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 15)
        lab.backgroundColor = ThemeColor
        lab.textAlignment = .Center
        // 设置fram
        lab.frame = CGRect(x: 0, y: 64 - 34, width: SCREENW, height: 34)
        lab.alpha = 0
        return lab
    }()


}

extension LLHomeTableViewController{
    
    //请求首页数据
    func loadStatusData(pullUp:Bool){
        
        var sinceId: Int64 = 0
        
        var maxId: Int64 = 0
        
        //上拉加载
        if pullUp {
            
            maxId = statuArray.last?.id ?? 0
            if maxId > 0{
                
                maxId -= 1
                
            }else{
                
                sinceId = statuArray.first?.id ?? 0
            }
            
        }
        
      LLStatusDAL.checkCache(sinceId, maxId: maxId
        , success: { (response) -> () in
            
            //结束动画
            self.activityView.stopAnimating()
            
            //结束刷新
            self.refresh.endRefreshing()
            
            //判断返回来的数据有值 并且是一个数组
            guard let res = response as?[[String: AnyObject]]else{
                
                print("请求错误")
                return
            
        }
            
        var tempArray: [LLStatusesModel] = [LLStatusesModel]()
            
            for dict in res{
                
                let statu = LLStatusesModel(dict: dict)
        
                tempArray.append(statu)
            }
            if pullUp {
                
                self.statuArray = self.statuArray + tempArray
            }else{
                
                self.statuArray = tempArray + self.statuArray
                
                self.pullDownTipLabelAnim(tempArray.count)
            }
           
            self.tableView.reloadData()
            
            }) { (error) -> () in
                
             print("失败:\(error)")
        }
    }
    
}

extension LLHomeTableViewController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
       return self.statuArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(statusCellId, forIndexPath: indexPath) as! LLStautsCell
        

        cell.status = statuArray[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if self.statuArray.count == indexPath.row + 1 && !activityView.isAnimating(){
            
            activityView.startAnimating()
            
            loadStatusData(activityView.isAnimating())
        }
    }
    
    func pullDownTipLabelAnim(count: Int){
        // 添加label
        if pullDownTipLabel.superview == nil {
            navigationController!.view.insertSubview(pullDownTipLabel, belowSubview: navigationController!.navigationBar)
        }
        var text = ""
        
        if count > 0{
            text = "您更新了\(count)条微博"
        }else {
            text = "您目前是最新的微博"
        }
        
        // 设置text
        pullDownTipLabel.text = text
        
        // 执行动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.pullDownTipLabel.alpha = 1
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, 34)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(0.25, delay: 2, options: [], animations: { () -> Void in
                    
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    
                    }, completion: { (_) -> Void in
                        self.pullDownTipLabel.alpha = 0
                })
                
        }
        
    }

}
